<?php

namespace app\service;


use app\model\Route;
use app\model\Theme;
use app\model\ThemeFile;
use think\facade\View;

class ThemeFileService
{
    public $themePath;
    public $rootPath;
    public $suffix;
    private $beautifyHtml;
    public $websitePath;
    public $originalPath;
    private $adminViewPath;

    public function __construct()
    {
        $this->themePath = config('view.view_dir_name');
        $this->rootPath = app()->getRootPath();
        $this->websitePath = $this->rootPath . 'public/themes/website/';
        $this->originalPath = $this->rootPath . 'public/themes/hc_original/';
        $this->adminViewPath = $this->rootPath . 'view/website/';
        $this->suffix = config('view.view_suffix');
        $this->beautifyHtml = new BeautifyHtmlService(array(
            'indent_inner_html' => false,
            'indent_char' => " ",
            'indent_size' => 2,
            'wrap_line_length' => 32786,
            'unformatted' => ['code', 'pre'],
            'preserve_newlines' => false,
            'max_preserve_newlines' => 32786,
            'indent_scripts'	=> 'normal', // keep|separate|normal
        ),true,true);
    }

    public function readSource($path): \think\response\Json
    {
        $path = $this->getFullPath($path);
        if(hcFileExist($path)){
            $ext = pathinfo(basename($path),PATHINFO_EXTENSION);
            $html = file_get_contents($path);
            if($ext == $this->suffix){
                $html =  $this->beautifyHtml->beautify($html);
            }
            return jsonReturn(0,'success',$html);
        }
        return jsonReturn(-1,'文件不存在');
    }

    /**
     * @throws \app\exception\ModelEmptyException
     * @throws \app\exception\ModelException
     * @throws \FormBuilder\Exception\FormBuilderException
     */
    public function compData($themeId, $siteId, $sellerId, $url,$block): string
    {
        $tmpData = $this->getThemeFileData($themeId, $siteId, $sellerId,$url);
        $blockData = $tmpData[$block];
        if(empty($blockData)){
            return '';
        }
        $formService = new ContentFormService();

        return $formService->getComponentForm($blockData);
    }

    /**
     * @throws \app\exception\ModelEmptyException
     * @throws \app\exception\ModelException
     * @throws \Exception
     */
    public function design($themeId, $siteId, $sellerId,$url='/'): string
    {
        $tmpData = $this->getThemeFileData($sellerId,$themeId, $siteId, $url);
        $tmpMore =$this->getReplaceParam($tmpData);
        $this->_initializeView($themeId, $siteId, $sellerId,$tmpMore);
        //使cdn设置生效
        $viewReplaceStr = [
            '__ADMIN_EDIT__' => $this->rootPath . 'view/common',
            '__ADMIN_STATIC__' => env('app_host') . '/view/common'
        ];

        $viewReplaceStr = array_merge($viewReplaceStr,$tmpMore);
        View::assign('theme',$tmpData);
        $content = file_get_contents($this-> adminViewPath .'3/default/portal/index.html');
        $content = str_replace(array_keys($viewReplaceStr), array_values($viewReplaceStr), $content);

        return  View::display($content);
    }

    /**
     * @throws \app\exception\ModelEmptyException
     * @throws \app\exception\ModelException
     */
    public function getThemeFileData($sellerId, $themeId, $siteId, $url)
    {
        $Route = new Route();
        $route = $Route->getRoute(['seller_id'=>$sellerId,'website_id'=>$siteId,'url'=>$url],['category'])['data'];
        $tmpTpl = $route['category']['list_tpl'];
        $ThemeFile = new ThemeFile();
        $themeFile = $ThemeFile->getThemeFile(['theme_id'=>$themeId,'seller_id'=>$sellerId,'website_id'=>$siteId,'file'=>$tmpTpl],['bigField'])['data']['bigField']['more'];
        return json_decode($themeFile,true);
    }

    // 文件更新
    public function updateResource($path,$content): \think\response\Json
    {
        $path = $this->getFullPath($path);
        if(hcFileExist($path)){
            $ext = pathinfo(basename($path),PATHINFO_EXTENSION);
            if($ext == $this->suffix){
                $content =  $this->beautifyHtml->beautify($content);
            }
            file_put_contents($path,$content);
            return jsonReturn(0,'success');
        }
        return jsonReturn(-1,'文件不存在');
    }

    public function getFullPath($path): string
    {
        return $this->adminViewPath . $path;
    }

    /**
     * @throws \app\exception\ModelEmptyException
     * @throws \app\exception\ModelException
     */
    protected function _initializeView($themeId, $siteId, $sellerId,$more)
    {
        $Theme = new Theme();
        $theme = $Theme->getTheme(['id'=>$themeId,'seller_id'=>$sellerId,'website_id'=>$siteId])['data'];
        $themeName = $theme['name'];
        //使cdn设置生效
        $viewReplaceStr = [
            '__TMPL__'     => env('app_host')."/view/website/{$siteId}/{$themeName}",
            '__STATIC__'   => env('app_host')."/view/website/{$siteId}/{$themeName}/static",
            '__ADMIN_EDIT__' => $this->rootPath . 'view/common',
            '__ADMIN_STATIC__' => env('app_host') . '/view/common'
        ];
        $viewReplaceStr = array_merge($viewReplaceStr,$more);
        $original = $this->adminViewPath;
        View::engine()->config([
            'view_path' => "{$original}/{$siteId}/{$themeName}/",
            'tpl_replace_string' => $viewReplaceStr,
//            'display_cache' => false,
            'tpl_cache' => false,
        ]);
    }

    protected function getReplaceParam($more): array
    {
        $tmp = [];
        foreach($more as $key => $val){
            foreach($val['element'] as $kk => $vv){
                if($vv['element_type'] == 'backend-tag'){
                    foreach($vv['value']['attr'] as $kkk => $vvv){
                        $tmp["\$theme['$key']['element']['$kk']['value']['attr']['$kkk']"] = "$vvv";
                    }
                }
            }
        }
        return $tmp;

    }

}